<template >
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
			<el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
			<el-breadcrumb-item>参数管理</el-breadcrumb-item>
			<el-breadcrumb-item>参数列表</el-breadcrumb-item>
		</el-breadcrumb>

		<!-- 列表内容卡片 -->
		<el-card>
			<!-- 警告区域 -->
			<el-alert title="注意: 只允许为第三季分类设置相关参数" type="warning" show-icon :closable="false"></el-alert>
			<el-row class="cat_opt">
				<el-col>
					<span>选择商品分类 :</span>
					<!-- 选择商品分类的级联选择框 -->
					<el-cascader
						v-model="selectedCateKeys"
						:options="cateList"
						:props="cateProps"
						@change="handleChange"
					></el-cascader>
				</el-col>
			</el-row>
			<!-- tab 标签页 -->
			<el-tabs v-model="activeName" @tab-click="handleTabClick">
				<!-- 添加动态参数面板 -->
				<el-tab-pane label="动态参数" name="many">
					<el-button type="primary" :disabled="isBtnDisabled" @click="addParamsDialog">添加参数</el-button>
					<!-- 参数展示 -->
					<el-table ref="manyTabDataRef" :data="manyTabData" style="width: 100%" border stripe>
						<el-table-column type="expand">
							<template slot-scope="scope">
								<el-tag
									closable
									v-for="(item,index) in scope.row.attr_vals"
									:key="index"
									@close="handleDeleteAttr(index,scope.row)"
								>{{item}}</el-tag>
								<!-- 输入的文本框 -->
								<el-input
									class="input-new-tag"
									v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue"
									ref="saveTagInput"
									size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)"
								></el-input>
								<el-button
									v-else
									class="button-new-tag"
									size="small"
									@click="showInput(scope.row)"
								>+ New Tag</el-button>

								<!-- <pre>{{scope.row}} </pre> -->
							</template>
						</el-table-column>
						<el-table-column type="index" :index="index" width="50"></el-table-column>
						<el-table-column prop="attr_name" label="参数名称"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button type="primary" icon="el-icon-edit" @click="editParamsName(scope.row)">编辑</el-button>
								<el-button type="danger" icon="el-icon-delete" @click="removeParams(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>

				<!-- 静态动态参数面板 -->
				<el-tab-pane label="静态参数" name="only">
					<el-button type="primary" :disabled="isBtnDisabled" @click="addParamsDialog">添加参数</el-button>
					<!-- 参数展示 -->
					<el-table ref="onlyTabDataRef" :data="onlyTabData" style="width: 100%" border stripe>
						<el-table-column type="expand">
							<template slot-scope="scope">
								<el-tag
									closable
									v-for="(item,index) in scope.row.attr_vals"
									:key="index"
									@close="handleDeleteAttr(index,scope.row)"
								>{{item}}</el-tag>
								<!-- 输入的文本框 -->
								<el-input
									class="input-new-tag"
									v-if="scope.row.inputVisible"
									v-model="scope.row.inputValue"
									ref="saveTagInput"
									size="small"
									@keyup.enter.native="handleInputConfirm(scope.row)"
									@blur="handleInputConfirm(scope.row)"
								></el-input>
								<el-button
									v-else
									class="button-new-tag"
									size="small"
									@click="showInput(scope.row)"
								>+ New Tag</el-button>

								<!-- <pre>{{scope.row}} </pre> -->
							</template>
						</el-table-column>
						<el-table-column type="index" :index="index" width="50"></el-table-column>
						<el-table-column prop="attr_name" label="参数名称"></el-table-column>
						<el-table-column label="操作">
							<template slot-scope="scope">
								<el-button type="primary" icon="el-icon-edit" @click="editParamsName(scope.row)">编辑</el-button>
								<el-button type="danger" icon="el-icon-delete" @click="removeParams(scope.row)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-tab-pane>
			</el-tabs>
		</el-card>

		<!-- 添加参数对话框 -->
		<el-dialog
			:title="'添加'+titleText"
			:visible.sync="addParamsDialogVisible"
			width="50%"
			@close="resetAddParamsFrom"
		>
			<el-form ref="addParamsFormRef" :model="addParamsForm" label-width="80px">
				<el-form-item label="活动名称" prop="attr_name">
					<el-input v-model="addParamsForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addParamsDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="addParams">确 定</el-button>
			</span>
		</el-dialog>
		<!-- 修改参数名称对话框 -->
		<el-dialog
			title="修改参数名"
			:visible.sync="editParamsNameDialogVisible"
			width="50%"
			@close="closeEditParamsDialog"
		>
			<el-form ref="editParamsNameFormRef" :model="editParamsNameForm" label-width="100px">
				<el-form-item label="输入参数名">
					<el-input autofocus clearable v-model="editParamsNameForm.attr_name"></el-input>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="editParamsNameDialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="editAttrName">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				cateList: [],
				cateProps: {
					expandTrigger: "hover",
					value: "cat_id",
					label: "cat_name",
					children: "children"
				},
				selectedCateKeys: [],
				// tab被激活的对应名称
				activeName: "many",
				// 动态面板数据
				manyTabData: [],
				// 静态面板数据
				onlyTabData: [],
				index: 1,
				addParamsDialogVisible: false,
				addParamsForm: {
					attr_name: ""
				},
				editParamsNameDialogVisible: false,
				editParamsNameForm: {}
			};
		},
		created() {
			this.getCateList();
		},
		methods: {
			async getCateList() {
				let { data: res } = await this.$http.get("categories");
				if (res.meta.status !== 200)
					return this.$message.error("获取商品分类失败");
				// this.$message.success("获取商品分类成功");
				// console.log(res);
				this.cateList = res.data;
				// console.log(this.cateList);
			},
			handleChange() {
				this.getParamData();
			},
			handleTabClick() {
				// console.log(this.activeName);
				this.getParamData();
			},
			// 获取参数数据
			async getParamData() {
				// console.log(this.selectedCateKeys);
				// 只能选第3级分类才让选择框显示
				if (this.selectedCateKeys.length !== 3) {
					this.selectedCateKeys = [];

					// 不在第3级分类时,给所有表格清空,防止不必要的操作
					this.manyTabData = [];
					this.onlyTabData = [];
					return;
				}
				// tab改变,发送请求获取添加资格
				let { data: res } = await this.$http.get(
					`categories/${this.cateId}/attributes`,
					{ params: { sel: this.activeName } }
				);
				// console.log(res.data);
				// console.log(this.activeName);

				// 先修改值，再赋值
				// 先循环遍历完毕后，再赋值
				// 里面涉及到数据绑定
				// 不是简单的 引用类型传递
				// 为展开行准备,将attr_vals转换为数组,这样可以方便渲染到标签中
				res.data.forEach(item => {
					item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
					// 控制文本框的显示与隐藏
					item.inputVisible = false;
					// 文本框中输入的值
					item.inputValue = "";
				});

				if (this.activeName == "many") {
					this.manyTabData = res.data;
					// console.log(this.manyTabData);
				} else {
					this.onlyTabData = res.data;
					// console.log(this.onlyTabData);
				}
				// 老师,刚刚没问为什么要换位置,现在有点儿想不通,
				// 放下面一样可以给每一项的inputVisible赋值,
				// 但是,点击事件为什么不能让输入框显示
			},
			addParamsDialog() {
				// if(this.activeName=='many'){return }

				this.addParamsDialogVisible = true;
			},
			addParams() {
				this.$refs.addParamsFormRef.validate(async valid => {
					// console.log(valid);
					let { data: res } = await this.$http.post(
						`categories/${this.cateId}/attributes`,
						{ attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName }
					);
					// console.log(res);
					if (res.meta.status !== 201) return this.$message.error("添加属性失败");
					this.$message.success("添加属性成功");
					this.getParamData();
					this.addParamsDialogVisible = false;
				});
			},
			resetAddParamsFrom() {
				this.$refs.addParamsFormRef.resetFields();
			},
			// 点击按钮,显示输入框
			showInput(row) {
				// console.log(row);
				row.inputVisible = true;

				// 让文本自动获得焦点
				// $nextTick 方法的作用,就是当页面上元素被重新渲染之后,才会指定回调函数中的代码
				this.$nextTick(() => {
					this.$refs.saveTagInput.$refs.input.focus();
				});
			},
			// 失去焦点或者按确认键
			handleInputConfirm(row) {
				// 判断输入框是否有内容
				if (row.inputValue.trim().length == 0) {
					row.inputValue = "";
					row.inputVisible = false;
					return;
				}
				row.attr_vals.push(row.inputValue);
				row.inputValue = "";
				row.inputVisible = false;
				this.saveAttrValue(row);
			},
			// 将对 attr_vals 的操作，保存到数据库
			async saveAttrValue(row) {
				let { data: res } = await this.$http.put(
					`categories/${this.cateId}/attributes/${row.attr_id}`,
					{
						attr_name: row.attr_name,
						attr_sel: row.attr_sel,
						attr_vals: row.attr_vals.join(" ")
					}
				);
				// console.log(res);
				if (res.meta.status !== 200) return this.$message.error("修改参数失败");
				this.$message.success("修改参数成功");
			},
			// 删除参数名称下的参数
			handleDeleteAttr(index, row) {
				// console.log(index);
				// console.log(row);
				row.attr_vals.splice(index, 1);
				this.saveAttrValue(row);
			},
			editParamsName(row) {
				console.log(row);
				// this.editParamsNameForm.cat_name = row.attr_name;
				this.editParamsNameForm = row;
				this.editParamsNameDialogVisible = true;
			},
			editAttrName() {
				this.$refs.editParamsNameFormRef.validate(async valid => {
					// console.log(valid);
					if (!valid) return;
					let { data: res } = await this.$http.put(
						`categories/${this.cateId}/attributes/${this.editParamsNameForm.attr_id}`,
						{
							attr_name: this.editParamsNameForm.attr_name,
							attr_sel: this.activeName
						}
					);
					console.log(res);
					// this.getCateList();
					this.editParamsNameDialogVisible = false;
				});
			},
			async removeParams(row) {
				const confirmResult = await this.$confirm(
					"此操作将永久删除该参数, 是否继续?",
					"提示",
					{
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					}
				).catch(err => err);
				if (confirmResult == "cancel") return this.$message.error("取消删除");
				let { data: res } = await this.$http.delete(
					`categories/${this.cateId}/attributes/${row.attr_id}`
				);
				// console.log(res);
				if (res.meta.status !== 200) return this.$message.error("删除失败");
				this.$message.success("删除成功");
				this.getParamData();
				// if(res.meta.)
			},
			closeEditParamsDialog() {
				this.getParamData();
			}
		},
		computed: {
			isBtnDisabled() {
				if (this.selectedCateKeys.length !== 3) {
					return true;
				} else {
					return false;
				}
			},
			// 分类id
			cateId() {
				if (this.selectedCateKeys.length === 3) {
					// console.log(this.selectedCateKeys[2]);
					return this.selectedCateKeys[2];
				} else {
					return null;
				}
			},
			// 添加属性title动态
			titleText() {
				if (this.activeName == "many") {
					return "  动态  属性";
				} else {
					return "  静态  属性";
				}
			}
		}
	};
</script>
<style lang="less" scoped>
	.cat_opt {
		margin: 15px 0;
	}
	.el-tag {
		margin: 10px;
	}
	.input-new-tag {
		width: 120px;
	}
</style>